package com.sk.weichat.ui.me.redpacket;

import android.animation.Animator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;

import android.os.Bundle;
import android.support.constraint.ConstraintLayout;

import android.support.constraint.ConstraintSet;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.transition.Scene;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.transition.Transition;
import android.transition.TransitionManager;
import android.transition.TransitionValues;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.facebook.drawee.view.SimpleDraweeView;
import com.githang.statusbar.StatusBarCompat;

import com.sk.weichat.R;

import com.sk.weichat.bean.redpacket.EventRedReceivedStatus;

import com.sk.weichat.bean.redpacket.RedpacketDetailBean;
import com.sk.weichat.helper.AvatarHelper;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.ui.WebAgreementActivity;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.ui.base.CoreManager;
import com.sk.weichat.ui.me.PersonalCenterActivity;
import com.sk.weichat.ui.tool.WebViewActivity;
import com.sk.weichat.util.Constants;
import com.sk.weichat.util.FrescoUtils;
import com.sk.weichat.util.ScreenUtil;
import com.sk.weichat.util.ToastUtil;

import com.sk.weichat.util.ViewPiexlUtil;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;
import okhttp3.Call;

import static android.support.constraint.ConstraintLayout.LayoutParams.PARENT_ID;
import static android.view.Window.FEATURE_CONTENT_TRANSITIONS;
import static com.sk.weichat.bean.redpacket.RedpacketDetailBean.RedpacketDetailBean_Status_Key;
import static com.xuan.xuanhttplibrary.okhttp.result.Result.CODE_SUCCESS;

/**
 * @author lzs
 * @date 2019/10/10
 * Email:343067508@qq.com
 **/
public class RedPacketActivity2 extends BaseActivity {
    RedpacketDetailBean redPacketBean;

    static Map<Integer, String> statusMap = new HashMap<>();
    boolean isOwner;
    boolean isGroup;

    boolean isRandom;

    TextView tvUnAbleView;
    TextView tvUnableOpenTips;
    SimpleDraweeView ivAvatar;
    TextView tvContent;
    TextView tvName;
    TextView tvStatus;
    TextView tvRecord;
    //领
    ImageView ivOpen;
    //红包状态
    int status = -1;

    String extraID;

    static {
        statusMap.put(RedpacketDetailBean.Status_unopen, "");
        statusMap.put(RedpacketDetailBean.Status_empty, "红包已抢光");
        statusMap.put(RedpacketDetailBean.Status_refunded, "红包已过期");
        statusMap.put(RedpacketDetailBean.Status_opened, "");
        statusMap.put(RedpacketDetailBean.Status_expire, "红包记录无法查看了");
    }

    ConstraintLayout constraintLayoutRoot;

    List<RedpacketDetailBean.ReceiveListBean> receiveListBeans = new ArrayList<>();
    BaseQuickAdapter<RedpacketDetailBean.ReceiveListBean, BaseViewHolder> adapter;

    NumberFormat numberFormat = new DecimalFormat("0.00");

    /**
     * @param context
     * @param redPacketBean 红包
     */
    public static final void startRedPacketActivity(Context context, RedpacketDetailBean redPacketBean, String extraID) {
        Intent intent = new Intent(context, RedPacketActivity2.class);
        intent.putExtra("RedPacketBean", redPacketBean);
        intent.putExtra("extraID", extraID);
        context.startActivity(intent);
    }

    //    public static final void startRedPacketActivityForResult(Activity context, RedpacketDetailBean redPacketBean, int requestCode) {
//        Intent intent = new Intent(context, RedPacketActivity.class);
//        intent.putExtra("RedPacketBean", redPacketBean);
//        context.startActivityForResult(intent, requestCode);
//    }
    AnimationDrawable animationDrawable;

    private void startAnimation() {
        animationDrawable = (AnimationDrawable) ivOpen.getBackground();
        //判断是否在运行
        if (null != animationDrawable && !animationDrawable.isRunning()) {
            //开启帧动画
            animationDrawable.start();
        }
    }

    private void stopAnimation() {
        if (null != animationDrawable) {
            animationDrawable.selectDrawable(0);
            animationDrawable.stop();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            getWindow().requestFeature(FEATURE_CONTENT_TRANSITIONS);
//        }
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_redpacket_scene1);
        //浅色状态栏字体图标
        StatusBarCompat.setLightStatusBar(getWindow(), false);
        ImageView ivBack = findViewById(R.id.iv_back);
        ConstraintLayout.LayoutParams lp = (ConstraintLayout.LayoutParams) ivBack.getLayoutParams();
        lp.topMargin += ScreenUtil.getStatusHeight(mContext);
        ivBack.setLayoutParams(lp);
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        redPacketBean = getIntent() != null ? getIntent().getParcelableExtra("RedPacketBean") : null;
        //redPacketBean.setStatus(0);

        extraID = getIntent() != null ? getIntent().getStringExtra("extraID") : "";
        tvUnAbleView = findViewById(R.id.tv_unable_view);
        tvUnableOpenTips = findViewById(R.id.tv_unable_open_tips);
        ivAvatar = findViewById(R.id.iv_avatar);
        //红包内容
        tvContent = findViewById(R.id.tv_content);
        tvName = findViewById(R.id.tv_name);
        tvStatus = findViewById(R.id.tv_status);
        tvRecord = findViewById(R.id.tv_record);
        ivOpen = findViewById(R.id.iv_get);

        constraintLayoutRoot = findViewById(R.id.constraint_set_root);
        if (redPacketBean != null) {
            status = redPacketBean.getStatus();
            //发红包者id
            String fromId = String.valueOf(redPacketBean.getUserId());
            //当前用户是否是发送者
            isOwner = fromId.equals(coreManager.getSelf().getUserId());
            //是否群聊
            isGroup = !TextUtils.isEmpty(redPacketBean.getRoomId());
            // 是否拼手气红包
            isRandom = redPacketBean.getType() == RedpacketDetailBean.type_random;

            //Log.e("lzs", "isOwner:" + isOwner + "  isGroup:" + isGroup + "  isOpened:" + isOpened + "  isRandom:" + isRandom + "  status:" + status);
            setAvatar();
            setFromUserName();
            setGetButton();
            setStatus();
            setTips();
            setContent();
            setUnAbleReason();
            setContract();

        }
        setMoreAction(status);
    }

    private void applyPersonalDetails(RedpacketDetailBean redPacketBean) {
        Transition transition = new Transition() {
            @Override
            public void captureStartValues(TransitionValues transitionValues) {

            }

            @Override
            public void captureEndValues(TransitionValues transitionValues) {

            }

            @Override
            public Animator createAnimator(ViewGroup sceneRoot, TransitionValues startValues, TransitionValues endValues) {
                return super.createAnimator(sceneRoot, startValues, endValues);
            }
        };

        TransitionManager.beginDelayedTransition(constraintLayoutRoot);
        ConstraintSet constraintSet1 = new ConstraintSet();
        constraintSet1.clone(mContext, R.layout.activity_redpacket_scene2);
        tvName.setText(redPacketBean.getNickname() + " 的红包");
        constraintSet1.applyTo(constraintLayoutRoot);
        ivAvatar.postDelayed(new Runnable() {
            @Override
            public void run() {
                TextView tvMoney = findViewById(R.id.tv_money);
                tvMoney.setText(numberFormat.format(redPacketBean.getReceiveMoney()));
                tvName.setTextColor(getResources().getColor(R.color.text_color_tip));
                tvName.setTextAppearance(mContext, R.style.text_bold);
                tvContent.setTextColor(getResources().getColor(R.color.color_FF919298));
            }
        }, 500);
    }

    private void applyMucDetails(RedpacketDetailBean redPacketBean) {
        //constrainLayout动画过渡
        TransitionManager.beginDelayedTransition(constraintLayoutRoot);
        ConstraintSet constraintSet1 = new ConstraintSet();
        constraintSet1.clone(mContext, R.layout.activity_redpacket_scene3);
        constraintSet1.applyTo(constraintLayoutRoot);

        ivAvatar.postDelayed(new Runnable() {
            @Override
            public void run() {
                setMucRedpacketDetails(redPacketBean);
            }
        }, 500);
    }


    private void goToWeb(String url) {
        Intent intent = new Intent(mContext, WebAgreementActivity.class);
        intent.putExtra("url", url);
        startActivity(intent);
    }

    //设置头像
    private void setAvatar() {
        if (status == RedpacketDetailBean.Status_expire) {
            ivAvatar.setVisibility(View.GONE);
            return;
        }
        if ((!isGroup && !isOwner && status == RedpacketDetailBean.Status_unopen) || (!isGroup && !isOwner && status == RedpacketDetailBean.Status_refunded) || (isRandom && isOwner && status == RedpacketDetailBean.Status_unopen) || (isRandom && !isOwner && status == RedpacketDetailBean.Status_unopen) ||
                (!isRandom && isGroup && !isOwner && redPacketBean.getStatus() == RedpacketDetailBean.Status_unopen) || (!isOwner && !isRandom && isGroup && status == RedpacketDetailBean.Status_empty) || (!isOwner && !isRandom && isGroup && status == RedpacketDetailBean.Status_refunded)) {
            ivAvatar.setVisibility(View.VISIBLE);
            FrescoUtils.loadImage(ivAvatar, AvatarHelper.getAvatarUrl(redPacketBean.getUserId() + "", true));
            ivAvatar.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    PersonalCenterActivity.start(mContext, redPacketBean.getUserId() + "");
                }
            });
        } else {
            ivAvatar.setVisibility(View.GONE);
        }
    }

    //设置发送者名称
    private void setFromUserName() {
        if (status == RedpacketDetailBean.Status_expire) {
            tvName.setVisibility(View.GONE);
            findViewById(R.id.iv_pin).setVisibility(View.GONE);
        } else if ((!isGroup && !isOwner && status == RedpacketDetailBean.Status_unopen) || (!isGroup && !isOwner && status == RedpacketDetailBean.Status_refunded) || (isRandom && isOwner && status == RedpacketDetailBean.Status_unopen) || (isRandom && !isOwner && status == RedpacketDetailBean.Status_unopen) || (!isOwner && !isRandom && isGroup && status == RedpacketDetailBean.Status_empty) || (!isOwner && !isRandom && isGroup && status == RedpacketDetailBean.Status_refunded) || (!isOwner && !isRandom && isGroup && status == RedpacketDetailBean.Status_unopen)) {
            if (isRandom && status != RedpacketDetailBean.Status_expire) {
                //拼手气红包，显示拼手气
                findViewById(R.id.iv_pin).setVisibility(View.VISIBLE);
            } else {
                findViewById(R.id.iv_pin).setVisibility(View.INVISIBLE);
            }
            tvName.setText("来自 " + redPacketBean.getNickname() + " 的红包");
            tvName.setVisibility(View.VISIBLE);
        } else {
            tvName.setVisibility(View.GONE);
            findViewById(R.id.iv_pin).setVisibility(View.GONE);
        }
    }

    //设置红包内容

    private void setContent() {
        if ((!isGroup && !isOwner && status == RedpacketDetailBean.Status_unopen) || (!isGroup && !isOwner && status == RedpacketDetailBean.Status_refunded) || (isGroup && isRandom && status == RedpacketDetailBean.Status_unopen) || (isGroup && !isRandom && !isOwner && status == RedpacketDetailBean.Status_unopen) || (!isOwner && !isRandom && isGroup && status == RedpacketDetailBean.Status_empty) || (!isOwner && !isRandom && isGroup && status == RedpacketDetailBean.Status_refunded)) {
            tvContent.setVisibility(View.VISIBLE);
            tvContent.setText(redPacketBean.getGreetings());
        } else {
            tvContent.setVisibility(View.GONE);
        }
    }

    private void setUnAbleReason() {
        if (isOwner && !isGroup) {
            if (status == RedpacketDetailBean.Status_unopen || status == RedpacketDetailBean.Status_opened || status == RedpacketDetailBean.Status_empty) {
                tvUnAbleView.setText(redPacketBean.getMoney() + "元红包已成功发给");
            } else if (redPacketBean.getStatus() == RedpacketDetailBean.Status_refunded) {
                tvUnAbleView.setText(redPacketBean.getMoney() + "元红包已过期");
            }
        }
        if (status == RedpacketDetailBean.Status_expire) {
            //过期72小时
            tvUnAbleView.setText("红包记录无法查看了");
        }
    }

    private void setTips() {
        if (isOwner && !isGroup) {
            tvUnableOpenTips.setVisibility(View.VISIBLE);
            if (status == RedpacketDetailBean.Status_unopen) {
                tvUnableOpenTips.setText("\"" + redPacketBean.getToUserName() + "\"" + "\n" + "有效期24小时");
            } else if (status == RedpacketDetailBean.Status_opened || status == RedpacketDetailBean.Status_empty) {
                tvUnableOpenTips.setText("\"" + redPacketBean.getToUserName() + "\"" + "\n" + "对方已领取");
            }
        } else {
            tvUnableOpenTips.setVisibility(View.INVISIBLE);
        }
    }

    //设置过期状态
    private void setStatus() {
        if ((!isOwner && !isGroup && status != RedpacketDetailBean.Status_expire) || (isGroup && !isRandom && status != RedpacketDetailBean.Status_expire && !isOwner && (status == RedpacketDetailBean.Status_refunded || status == RedpacketDetailBean.Status_empty))) {
            tvStatus.setText(statusMap.get(status));
        }
    }

    //设置领取按钮
    private void setGetButton() {
        if ((!isOwner && !isGroup && status == RedpacketDetailBean.Status_unopen) || (isRandom && status == RedpacketDetailBean.Status_unopen) || (!isRandom && isGroup && !isOwner && status == RedpacketDetailBean.Status_unopen)) {
            ivOpen.setVisibility(View.VISIBLE);
            ivOpen.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ivOpen.setEnabled(false);
                    openRedPacket(redPacketBean.getId());
                }
            });
        } else {
            ivOpen.setVisibility(View.GONE);
        }
    }

    //设置右上角按钮
    private void setMoreAction(int status) {
        if ((isRandom && !isOwner && status == RedpacketDetailBean.Status_unopen) || (isGroup && !isRandom && !isOwner && status == RedpacketDetailBean.Status_unopen)) {
            tvRecord.setVisibility(View.GONE);
        } else {
            tvRecord.setVisibility(View.VISIBLE);
        }
        if (isOwner && isRandom && status == RedpacketDetailBean.Status_unopen) {
            //查看详情
            tvRecord.setText(getString(R.string.view_detail));
            tvRecord.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //跳转红包详情
                    MucRedPacketDetailsActivity.startRedPacketDetailsActivity(mContext, redPacketBean);
                }
            });
        } else {
            //交易记录
            tvRecord.setText(getString(R.string.trade_record));
            tvRecord.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //跳转交易记录
                    String url = coreManager.getConfig().TRADE_RECORDE + "?access_token=" + coreManager.getSelfStatus().accessToken + "&time=" + System.currentTimeMillis() / 1000;
                    WebViewActivity.start(mContext, url, false);
                }
            });
        }
    }

    TextView tvContract;

    /**
     * 设置协议
     */
    private void setContract() {
        if (status != RedpacketDetailBean.Status_unopen || status == RedpacketDetailBean.Status_unopen && isOwner && !isGroup) {
            return;
        }
        //钱包协议
        tvContract = findViewById(R.id.tv_contract);

        SpannableString spannableString = new SpannableString(getString(R.string.redpacket_contract_of_wallet));
        ClickableSpan clickableSpan = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                goToWeb(coreManager.getConfig().WALLET_CONTRACT);
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(getResources().getColor(R.color.color_FFA889));
                ds.setUnderlineText(false);
                ds.clearShadowLayer();
            }
        };
        spannableString.setSpan(clickableSpan, 0, spannableString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        tvContract.setMovementMethod(LinkMovementMethod.getInstance());
        tvContract.setHighlightColor(Color.TRANSPARENT);
        tvContract.setText(spannableString);
        tvContract.setVisibility(View.VISIBLE);
    }


    /**
     * 打开红包
     */
    private void openRedPacket(String id) {
        startAnimation();
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("id", id);
        HttpUtils.get().url(coreManager.getConfig().REDPACKET_OPEN)
                .params(params)
                .build()
                .execute(new BaseCallback<RedpacketDetailBean>(RedpacketDetailBean.class) {
                    @SuppressLint("SetTextI18n")
                    @Override
                    public void onResponse(ObjectResult<RedpacketDetailBean> result) {
                        ivOpen.setEnabled(true);
                        stopAnimation();
                        if (result.getResultCode() == CODE_SUCCESS) {
                            //Log.e("lzs", "领取成功 红包id:" + result.getData().getId() + "  status :" + result.getData().getStatus());
                            EventBus.getDefault().post(new EventRedReceivedStatus(extraID, result.getData().getStatus()));
                            status = result.getData().getStatus();
                            if (status == RedpacketDetailBean.Status_expire || isGroup && !isOwner && status != RedpacketDetailBean.Status_opened && !isRandom) {
                                setAvatar();
                                setFromUserName();
                                setGetButton();
                                setStatus();
                                setTips();
                                setContent();
                                setUnAbleReason();
                                setContract();
                                tvContract.setVisibility(View.GONE);
                                setMoreAction(status);
                                return;
                            }
                            if ((!isRandom && !isOwner || !isGroup && !isOwner)) {
                                applyPersonalDetails(result.getData());
                            } else {
                                //切换
                                statusMap.put(RedpacketDetailBean.Status_empty, "已抢光");
                                statusMap.put(RedpacketDetailBean.Status_refunded, "已过期");
                                applyMucDetails(result.getData());
                            }
                        } else if (result.getResultCode() == 1040329) {
                            //当日领取红包上限
                            tvContent.setVisibility(View.GONE);
                            tvName.setVisibility(View.GONE);
                            tvStatus.setVisibility(View.GONE);
                            ivAvatar.setVisibility(View.GONE);
                            ivOpen.setVisibility(View.GONE);
                            findViewById(R.id.iv_pin).setVisibility(View.GONE);
                            findViewById(R.id.tv_contract).setVisibility(View.GONE);
                            tvUnAbleView.setVisibility(View.VISIBLE);
                            tvUnableOpenTips.setVisibility(View.VISIBLE);
                            tvUnableOpenTips.setText(getResources().getString(R.string.tips_recieve_redpacket_exceed));
                            tvUnAbleView.setText(getResources().getString(R.string.recieve_redpacket_exceed));
                        } else {
                            ToastUtil.showToast(mContext, result.getResultMsg());
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        ivOpen.setEnabled(true);
                        ToastUtil.showToast(mContext, getString(R.string.net_exception));
                        stopAnimation();
                    }
                });
    }

    TextView tvMoney;
    TextView tvYuan;

    private void setMucRedpacketDetails(RedpacketDetailBean redPacketBean) {
        RecyclerView recyclerView = findViewById(R.id.recyclerview);
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        adapter = new BaseQuickAdapter<RedpacketDetailBean.ReceiveListBean, BaseViewHolder>(R.layout.item_red_packet_details_reciever, receiveListBeans) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

            @Override
            protected void convert(BaseViewHolder holder, RedpacketDetailBean.ReceiveListBean item) {
                holder.addOnClickListener(R.id.iv_avatar);
                //头像
                FrescoUtils.loadImage((SimpleDraweeView) holder.getView(R.id.iv_avatar), AvatarHelper.getAvatarUrl(item.getUserId() + "", true));
                holder.setText(R.id.tv_name, item.getNickname());
                //时间
                holder.setText(R.id.tv_time, sdf.format(new Date(item.getReceiveTime() * 1000)));
                //
                holder.setText(R.id.tv_money, item.getReceiveMoney() + " 元");
                //判断是否是最佳
                if (item.getIsMost() == 0) {
                    holder.setTextColor(R.id.tv_money, getResources().getColor(R.color.text_color_main));
                    holder.getView(R.id.tv_best).setVisibility(View.INVISIBLE);
                } else {
                    holder.getView(R.id.tv_best).setVisibility(View.VISIBLE);
                    holder.setTextColor(R.id.tv_money, getResources().getColor(R.color.color_ff2626));
                }
            }
        };
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.iv_avatar) {
                    PersonalCenterActivity.start(mContext, receiveListBeans.get(position).getUserId() + "");
                }
            }
        });

        View headerView = LayoutInflater.from(mContext).inflate(R.layout.layout_header_redpacket, null);
        //头像
        SimpleDraweeView ivAvatar = headerView.findViewById(R.id.iv_avatar);
        FrescoUtils.loadImage(ivAvatar, AvatarHelper.getAvatarUrl(redPacketBean.getUserId() + "", true));
        ivAvatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PersonalCenterActivity.start(mContext, redPacketBean.getUserId() + "");
            }
        });
        //昵称
        TextView tvName = headerView.findViewById(R.id.tv_name);
        tvName.setText(redPacketBean.getNickname() + " 的红包");

        if (isRandom) {
            //拼手气红包，显示拼手气
            Drawable drawable = getResources().getDrawable(R.mipmap.icon_pin);
            drawable.setBounds(new Rect(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()));
            tvName.setCompoundDrawables(null, null, drawable, null);
        } else {
            ConstraintLayout.LayoutParams lp2 = (ConstraintLayout.LayoutParams) tvName.getLayoutParams();
            lp2.leftMargin = 0;
            tvName.setLayoutParams(lp2);
        }
        //红包内容
        TextView tvContent = headerView.findViewById(R.id.tv_content);
        tvContent.setText(redPacketBean.getGreetings());
        tvMoney = headerView.findViewById(R.id.tv_money);
        tvYuan = headerView.findViewById(R.id.tv_yuan);
        //设置金额
        setMoney(redPacketBean);

        //红包状态
        TextView tvStatus = headerView.findViewById(R.id.tv_status);
        tvStatus.setText(statusMap.get(redPacketBean.getStatus()));
        //已领取个数
        TextView tvDesc = headerView.findViewById(R.id.tv_desc);
        if (redPacketBean.getCount() == redPacketBean.getReceiveCount()) {
            //已抢光
            tvDesc.setText("已领取" + redPacketBean.getReceiveCount() + "个，" + caculateTime(redPacketBean.getSendTime(), redPacketBean.getEndTime()) + "被抢光");
        } else {
            //未抢光
            tvDesc.setText("已领取" + redPacketBean.getReceiveCount() + "个");
        }
        TextView tvTotal = headerView.findViewById(R.id.tv_total);
        if (coreManager.getSelf().getUserId().equals(String.valueOf(redPacketBean.getUserId()))) {
            //发红包者自己，可以看到总金额
            tvTotal.setText("共" + redPacketBean.getCount() + "个，总金额" + redPacketBean.getMoney() + "元");
        } else {
            //其他用户
            tvTotal.setText("共" + redPacketBean.getCount() + "个");
        }
        adapter.addHeaderView(headerView);
        recyclerView.setAdapter(adapter);
        //获取红包详情
        getDetails(redPacketBean.getId());
    }

    private String caculateTime(long sendTime, long endTime) {
        long time = endTime - sendTime;
        if (time / 60 == 0) {
            return time + "秒";
        } else if (time / 60 / 60 == 0) {
            return time / 60 + "分钟";
        } else {
            return time / 60 / 60 + "小时";
        }
    }

    private void setMoney(RedpacketDetailBean redPacketBean) {
        if (isRandom && isGroup && isOwner && redPacketBean.getStatus() == RedpacketDetailBean.Status_opened || isRandom && !isOwner && redPacketBean.getStatus() == RedpacketDetailBean.Status_opened) {
            tvMoney.setVisibility(View.VISIBLE);
            tvYuan.setVisibility(View.VISIBLE);
            //显示领取金额
            tvMoney.setText(numberFormat.format(redPacketBean.getReceiveMoney()));
        } else if (!isRandom && isGroup && isOwner && redPacketBean.getStatus() == RedpacketDetailBean.Status_opened || !isRandom && isGroup && isOwner && redPacketBean.getStatus() == RedpacketDetailBean.Status_unopen || isRandom && isOwner && redPacketBean.getStatus() == RedpacketDetailBean.Status_unopen) {
            tvYuan.setVisibility(View.GONE);
            tvMoney.setVisibility(View.GONE);
        } else if (isRandom && isOwner && redPacketBean.getStatus() != RedpacketDetailBean.Status_empty && redPacketBean.getStatus() != RedpacketDetailBean.Status_refunded) {
            tvMoney.setVisibility(View.VISIBLE);
            tvYuan.setVisibility(View.VISIBLE);
        } else {
            tvYuan.setVisibility(View.INVISIBLE);
            tvMoney.setVisibility(View.INVISIBLE);
        }
    }

    // 点击红包 查询红包状态
    public void getDetails(String id) {
        final String token = CoreManager.requireSelfStatus(mContext).accessToken;
        HashMap<String, String> params = new HashMap<>();
        params.put("access_token", token);
        params.put("id", id);
        HttpUtils.post().url(CoreManager.requireConfig(mContext).RENDPACKET_GET)
                .params(params)
                .build()
                .execute(new BaseCallback<RedpacketDetailBean>(RedpacketDetailBean.class) {

                    @Override
                    public void onResponse(ObjectResult<RedpacketDetailBean> result) {
                        if (result.getResultCode() == 1 && result.getData() != null) {
                            receiveListBeans.clear();
                            receiveListBeans.addAll(result.getData().getReceiveList());
                            adapter.notifyDataSetChanged();
                            setMoreAction(result.getData().getStatus());
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                    }
                });
    }
}
